package com.ciaojian.worker.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ciaojian.core.enums.business.MaterialApplyRecordLogisticsEnum;
import com.ciaojian.core.enums.business.MaterialApplyRecordStatusEnum;
import com.ciaojian.core.model.*;
import com.ciaojian.core.util.LogUtil;
import com.ciaojian.core.util.Result;
import com.ciaojian.worker.model.param.StoreMaterialApplyRecordParam;
import com.ciaojian.worker.service.MaterialApplyRecordMaterialServiceImpl;
import com.ciaojian.worker.service.MaterialApplyRecordServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

/**
 * @author Atlakyn
 */
@Validated
@Api(tags = "门店库存")
@RestController
@RequestMapping("/store-material")
public class StoreMaterialController {
    @Resource
    private MaterialApplyRecordMaterialServiceImpl materialApplyRecordMaterialService;
    @Resource
    private MaterialApplyRecordServiceImpl materialApplyRecordService;

    @ApiOperation("门店物资清单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "物资类型"),
            @ApiImplicitParam(name = "storeId", value = "门店ID")
    })
    @GetMapping("/list-store")
    public Result listStore(@NotBlank(message = "物资类型不能为空") String type, @NotNull(message = "门店ID不能为空") Integer storeId) {
        LambdaQueryWrapper<StoreMaterial> queryWrapper = new LambdaQueryWrapper<StoreMaterial>()
                .eq(StoreMaterial::getType, type)
                .eq(StoreMaterial::getStoreId, storeId);
        return Result.ok(new StoreMaterial().selectList(queryWrapper));
    }

    @ApiOperation("总物资清单")
    @ApiImplicitParams(@ApiImplicitParam(name = "type", value = "物资类型"))
    @GetMapping("/list-material")
    public Result listMaterial(@NotNull(message = "物资类型不能为空") String type) {
        LambdaQueryWrapper<Material> queryWrapper = new LambdaQueryWrapper<Material>()
                .eq(Material::getType, type);
        return Result.ok(new Material().selectList(queryWrapper));
    }

    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("资产申请")
    @PostMapping("/apply")
    public Result apply(@RequestBody @Validated StoreMaterialApplyRecordParam param) {
        Worker worker = new Worker().selectById(param.getWorkerId());
        Store store = new Store().selectById(param.getStoreId());
        // 插入新的申请记录
        MaterialApplyRecord materialApplyRecord = new MaterialApplyRecord();
        materialApplyRecord.setStoreId(param.getStoreId())
                .setWorkerId(param.getWorkerId())
                .setRemark(store.getTitle() + "-" + worker.getName() + "提交 物资申请")
                .insert();

        param.getMaterialApplyRecordMaterialList().forEach(i -> i.setApplyId(materialApplyRecord.getId()));

        return Result.save(materialApplyRecordMaterialService.saveBatch(param.getMaterialApplyRecordMaterialList()));
    }

    @ApiOperation("展示申请记录")
    @GetMapping("/list-apply/{storeId}/{workerId}")
    public Result listApply(@PathVariable Integer storeId,
                            @PathVariable Integer workerId,
                            MaterialApplyRecordStatusEnum status,
                            @RequestParam(defaultValue = "0") Integer pageNo,
                            @RequestParam(defaultValue = "6") Integer pageSize) {
        return Result.ok(materialApplyRecordService.getBaseMapper().findApplyRecord(
                storeId,
                workerId,
                status,
                new Page<>(pageNo, pageSize)));
    }

    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("撤回申请")
    @PutMapping("/withdraw")
    public Result withdrawApply(@NotNull(message = "'recordId' not null") Integer recordId) {
        MaterialApplyRecord materialApplyRecord = new MaterialApplyRecord().selectById(recordId);
        Assert.notNull(materialApplyRecord, "申请记录不存在");
        LogUtil.writeBusinessLog(String.format("当前申请记录:%s 的状态为: %s", materialApplyRecord.getId(), materialApplyRecord.getStatus()));
        Assert.isTrue(materialApplyRecord.getStatus().equals(MaterialApplyRecordStatusEnum.WAIT), "当前不可撤回");

        return Result.save(materialApplyRecordService.withdraw(materialApplyRecord));
    }

    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("收货")
    @PutMapping("/receipt")
    public Result receipt(@NotNull(message = "请选择要收货的申请记录") Integer recordId) {
        MaterialApplyRecord materialApplyRecord = new MaterialApplyRecord().selectById(recordId);
        Assert.notNull(materialApplyRecord, "收货记录不存在");
        Assert.isTrue(materialApplyRecord.getLogistics() != MaterialApplyRecordLogisticsEnum.RECEIVED, "已收货");

        materialApplyRecord.setLogistics(MaterialApplyRecordLogisticsEnum.RECEIVED);
        return Result.save(materialApplyRecord.updateById());
    }
}
